﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Linq;
using Silvermoon.Controls.Classes;
using Silvermoon.Controls.Base;

namespace Silvermoon.Controls.Toolbars
{
    public class ButtonCollection : TypedControlCollection<Toolbar, ButtonBase>
    {
        const int MaxButtons = 5;

        private bool isInvalidated;
        private ICollection<ButtonBase> buttons;
        private ControlEventArgs controlArgs = new ControlEventArgs();

        public ButtonCollection(Toolbar owner) : base(owner) { }

        public bool IsInvalidated { get { return isInvalidated; } }

        protected override void InsertItem(int index, ButtonBase item)
        {
            if (Count >= MaxButtons) throw new ArgumentOutOfRangeException("Cannot add more than 5 buttons.");
            OnListChanging();
            base.InsertItem(index, item);
            OnListChanged();

        }

        protected override void RemoveItem(int index)
        {
            OnListChanging();
            base.RemoveItem(index);
            OnListChanged();
        }

        protected override void OnClear()
        {
            OnListChanging();
            foreach (var button in this)
            {
                button.Dispose();
            }
            base.OnClear();
            OnListChanged();
        }

        private void OnListChanging()
        {
            if (!isInvalidated && Parent.AreButtonsShown)
            {
                buttons = this.ToArray();
                isInvalidated = true;
                Parent.InvalidateButtons();
            }
        }

        private void OnListChanged()
        {
            if (ListChanged != null) ListChanged(this, EventArgs.Empty);
        }

        //public event EventHandler<ControlEventArgs> ControlAdded;
        //public event EventHandler<ControlEventArgs> ControlRemoved;
        public event EventHandler ListChanged;


        public void AddRange(params ButtonBase[] buttons)
        {
            foreach (ButtonBase b in buttons) Add(b);
        }

        public void Validate()
        {
            if (isInvalidated)
            {
                isInvalidated = false;
                Parent.Invalidate(InvalidationFlag.Layout);
            }
        }

        public ICollection<ButtonBase> GetVisibleButtons()
        {
            return isInvalidated ? buttons : this;
        }


    }
}
